<?php

namespace app\admin\controller\health\user;

use app\common\controller\Backend;
use app\health\model\HealthUser;
use app\health\model\HealthUserWithdraw;

class WalletApply extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HealthUserWithdraw();
        $this->assignconfig('status_map', HealthUserWithdraw::STATUS_MAP);
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $nobuildfields = ['real_name', 'mobile'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);
            $total = $this->buildSearch()
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->buildSearch()
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        $this->assign('title', '用户提现');
        return $this->view->fetch();
    }

    /**
     * 提现搜索
     *
     * @return object
     */
    public function buildSearch()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $real_name = isset($filter['real_name']) ? $filter['real_name'] : '';
        $mobile = isset($filter['mobile']) ? $filter['mobile'] : '';

        // 当前表名
        $tableName = $this->model->getQuery()->getTable();

        $applys = $this->model;

        // 购买人查询
        if ($real_name || $mobile) {
            $applys = $applys->whereExists(function ($query) use ($real_name, $mobile, $tableName) {
                $userTableName = (new HealthUser())->getQuery()->getTable();
                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . '.user_id');
                if ($real_name) {
                    $query = $query->where('real_name', 'like', "%{$real_name}%");
                }

                if ($mobile) {
                    $query = $query->where('mobile', 'like', "%{$mobile}%");
                }
                return $query;
            });
        }
        return $applys;
    }

    /**
     * 审核提现申请
     * @param [type] $ids
     * @Author 张旭鹏
     * @DateTime 2023-07-05
     */
    public function handle($ids)
    {
        $successCount = 0;
        $failedCount = 0;
        $ids = explode(',', $ids);
        $applyList = $this->model->where('id', 'in', $ids)->select();
        if (!$applyList) {
            $this->error('未找到该提现申请');
        }
        $operate = $this->request->post('operate');
        foreach ($applyList as $apply) {
            Db::startTrans();
            try {
                switch ($operate) {
                    case '1': //统一
                        WithDraw::handleAgree($apply);
                        $apply->status === 1 ? $successCount++ : $failedCount++;
                        break;
                    case '2': //打款
                        WithDraw::handleWithdraw($apply);
                        $apply->status === 2 ? $successCount++ : $failedCount++;
                        break;
                    case '2': //拒绝
                        $rejectInfo = $this->request->post('rejectInfo');
                        if (!$rejectInfo) {
                            throw new \Exception('请输入拒绝原因');
                        }
                        WithDraw::handleReject($apply, $rejectInfo);
                        $apply->status === -1 ? $successCount++ : $failedCount++;;
                        break;
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                WithDraw::handleLog($apply, '失败: ' . $e->getMessage());
                $failedCount++;
                $lastErrorMessage = $e->getMessage();
            }
        }
        if (count($ids) === 1) {
            if ($successCount) $this->success('操作成功');
            if ($failedCount) $this->error($lastErrorMessage);
        } else {
            $this->success('成功: ' . $successCount . '笔' . ' | 失败: ' . $failedCount . '笔');
        }
    }
}
